import requests
import os
import sys
sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')

import django
django.setup()

from apps.flowers.models import Flower
from common.utils.oss_utils import FileOss

def fix_pink_tulip():
    """修复粉郁金香花束图片"""
    
    # 使用Pixabay的郁金香图片
    pink_tulip_urls = [
        "https://cdn.pixabay.com/photo/2017/04/10/22/28/tulips-2218771_960_720.jpg",
        "https://cdn.pixabay.com/photo/2016/04/15/04/02/tulips-1330494_960_720.jpg",
        "https://cdn.pixabay.com/photo/2017/03/27/13/54/tulips-2178718_960_720.jpg",
        "https://cdn.pixabay.com/photo/2018/04/05/14/09/tulips-3292932_960_720.jpg"
    ]
    
    flower = Flower.objects.filter(name='粉郁金香花束').first()
    if not flower:
        print("未找到粉郁金香花束")
        return
    
    oss_client = FileOss()
    
    for i, url in enumerate(pink_tulip_urls):
        try:
            print(f"尝试下载图片 {i+1}: {url}")
            
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            
            # 上传到OSS
            oss_path = "flowers/粉郁金香花束.jpg"
            oss_url = oss_client.get_oss_image_url(oss_path, response.content)
            
            if oss_url:
                flower.image = oss_url
                flower.save()
                print(f"✓ 成功更新粉郁金香花束图片: {oss_url}")
                return
            else:
                print("✗ OSS上传失败")
                
        except Exception as e:
            print(f"✗ 下载失败: {e}")
            continue
    
    print("✗ 所有图片都下载失败")

if __name__ == "__main__":
    fix_pink_tulip()